export class AudioMgr{

    bgmVolume = 1.0;
    sfxVolume = 1.0;
    bgmAudioID = -1;

    sfxAudioID = -1;

    init(){
        let t = cc.sys.localStorage.getItem('bgmVolume');
        if(t != null){
            this.bgmVolume = parseFloat(t);
        }

        let t1 = cc.sys.localStorage.getItem('sfxVolume');
        if(t1 != null){
            this.sfxVolume = parseFloat(t1);
        }

        
        cc.game.on(cc.game.EVENT_HIDE, () => {
            console.log('暂停所有音乐');
            cc.audioEngine.pauseAll();
        });

        cc.game.on(cc.game.EVENT_SHOW, () => {
            console.log('恢复所有之前暂停的所有音频');
            cc.audioEngine.resumeAll();
        });
    }


    playBGM(url: string){
        const audioUrl = this.getUrl(url);
        if(this.bgmAudioID >= 0){
            cc.audioEngine.stop(this.bgmAudioID);
        }
        this.bgmAudioID = cc.audioEngine.play(audioUrl, true, this.bgmVolume);
    }


    playSFX(url: string){
        const audioUrl = this.getUrl(url);
        if(this.sfxVolume > 0){
            cc.audioEngine.play(audioUrl, false, this.sfxVolume);
        }
    }


    getUrl(url: string): string{
        return cc.url.raw('resources/sounds/' + url);
    }

    /**
     * 把音效音量设置保存到localStorage中
     */
    setSFXVolume(v){
        if(this.sfxVolume != v){
            cc.sys.localStorage.setItem('sfxVolume', v);
            this.sfxVolume = v;
        }
    }

    /**
     * 把背景音乐音量设置保存到localStorage中,并设置音量
     */
    setBGMVolume(v: number, force?){
        // if(this.bgmAudioID >= 0){
        //     if(v > 0){
        //         cc.audioEngine.resume(this.bgmAudioID);
        //     }
        //     else{
        //         cc.audioEngine.pause(this.bgmAudioID);
        //     }
        // }
        if(this.bgmVolume != v || force){
            cc.sys.localStorage.setItem('bgmVolume', v);
            this.bgmVolume = v;
            cc.audioEngine.setVolume(this.bgmAudioID, v);
        }
    }

    /**暂停所有音效音乐 */
    pauseAll(){
        cc.audioEngine.pauseAll();
    }

    /**恢复暂停的所有音效音乐 */
    resumeAll(){
        cc.audioEngine.resumeAll();
    }
}